//
//  MyBalanceTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/7.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import MJRefresh
import DZNEmptyDataSet

class MyBalanceTableViewController: BaseTableViewController {
    
    var page = 1
    
    var dataArray = [UserMoneyModel]()
    
    @IBOutlet weak var balanceLabel: UILabel!
    
    var balance = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        
        self.title = "我的余额"
        if self.balance != "" {
             self.balanceLabel.attributedText = Utils.changeLabelTextFontSize(normalString: "￥" + self.balance, changeString: self.balance.getPriceInteger(), font: UIFont.systemFont(ofSize: 40))
        }else{
            self.getUserPerson()
        }
        self.tableView.emptyDataSetDelegate = self
        self.tableView.emptyDataSetSource = self
       
        self.tableView.mj_footer = MJRefreshAutoFooter.init(refreshingBlock: { [weak self] in
            self?.page = (self?.page)! + 1
            self?.getMyBalance()
        })
        PKhud.show()
        self.getMyBalance()
    }
    
    func getUserPerson(){
        HttpRequest.requestData(.post, URLString: Api.userPerson.rawValue, parameters: nil) { (result) in
            if result["msg"] as! String == "success"{
                let dic = result["data"] as! [String:Any]
                self.balance = "\(dic["money"] as! Double)"
                self.balanceLabel.attributedText = Utils.changeLabelTextFontSize(normalString: "￥" + self.balance, changeString: self.balance.getPriceInteger(), font: UIFont.systemFont(ofSize: 40))
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func getMyBalance(){
        
        HttpRequest.requestData(.post, URLString: Api.userMoney.rawValue, parameters: ["pageNum":self.page,"pageSize":10]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if let array = [UserMoneyModel].deserialize(from: result["data"] as? [Any]) as? [UserMoneyModel]{
                    if self.page == 1 {
                        self.dataArray = array
                    }else{
                        self.dataArray = self.dataArray + array
                    }
                    if  array.count < 10 {
                        self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    }
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }

    // MARK:充值
    @IBAction func rechargeMethod(_ sender: UIButton) {
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "BalanceRechargeTableViewController") as! BalanceRechargeTableViewController
        ctrl.myBalance = self.balance
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataArray.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BalanceDetailTableViewCell", for: indexPath) as! BalanceDetailTableViewCell
        cell.reload(withModel: self.dataArray[indexPath.row])

        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 75
    }
    
}


extension MyBalanceTableViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate {
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let str = "暂无支出哦~"
        let attribute = NSMutableAttributedString.init(string: str)
        attribute.addAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 14),
                                 NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "666666")], range: NSRange.init(location: 0, length: str.count))
        
        return attribute
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return UIImage.init(named: "img_Defaultheadimage")
    }
}
